package com.plumdong.sms.service;

import com.google.protobuf.ProtocolStringList;
import com.plumdong.sms.proto.SmsProto;
import com.plumdong.sms.proto.SmsServiceGrpc;
import io.grpc.stub.StreamObserver;

public class SmsService extends SmsServiceGrpc.SmsServiceImplBase {
    /**
     * @param request
     * @param responseObserver
     */
    @Override
    public void sendSms(SmsProto.SmsRequest request, StreamObserver<SmsProto.SmsResponse> responseObserver) {
        ProtocolStringList phoneNumberList = request.getPhoneNumberList();
        for (String phone : phoneNumberList) {
            SmsProto.SmsResponse response = SmsProto.SmsResponse.newBuilder().setResult(request.getContent() + "," + phone + "已发送！").build();
            responseObserver.onNext(response);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        responseObserver.onCompleted();
    }

    /**
     * @param responseObserver
     */
    @Override
    public StreamObserver<SmsProto.PhoneNumberRequest> createPhone(StreamObserver<SmsProto.PhoneNumberResponse> responseObserver) {
        return super.createPhone(responseObserver);
    }

    /**
     * @param responseObserver
     */
    @Override
    public StreamObserver<SmsProto.PhoneNumberRequest> createAndSendSms(StreamObserver<SmsProto.PhoneNumberResponse> responseObserver) {
        return new StreamObserver<SmsProto.PhoneNumberRequest>() {
            int i = 0;
            @Override
            public void onNext(SmsProto.PhoneNumberRequest phoneNumberRequest) {
                System.out.println(phoneNumberRequest.getPhoneNumber() + " 手机号已登记！");
                responseObserver.onNext(SmsProto.PhoneNumberResponse.newBuilder().setResult(phoneNumberRequest.getPhoneNumber() + " 手机号已登记！此消息已发送部门经理").build());
                responseObserver.onNext(SmsProto.PhoneNumberResponse.newBuilder().setResult(phoneNumberRequest.getPhoneNumber() + " 手机号已登记！此消息已发送副总经理").build());
                responseObserver.onNext(SmsProto.PhoneNumberResponse.newBuilder().setResult(phoneNumberRequest.getPhoneNumber() + " 手机号已登记！此消息已发送总经理").build());
                i++;
            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onCompleted() {
                responseObserver.onCompleted();
            }
        };

    }
}
